<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="40" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-user">
            <svg-icon icon-class="peoples" class-name="card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">总用户数</div>
            <count-to :start-val="0" :end-val="overviewData.totalUsers || 0" :duration="2600" class="card-panel-num" />
            <div class="card-panel-sub">
              今日新增: {{ overviewData.todayNewUsers || 0 }}
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-video">
            <i class="el-icon-video-camera card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">总视频数</div>
            <count-to :start-val="0" :end-val="overviewData.totalVideos || 0" :duration="3000" class="card-panel-num" />
            <div class="card-panel-sub">
              今日新增: {{ overviewData.todayNewVideos || 0 }}
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-comment">
            <i class="el-icon-chat-line-round card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">总评论数</div>
            <count-to :start-val="0" :end-val="overviewData.totalComments || 0" :duration="3200" class="card-panel-num" />
            <div class="card-panel-sub">
              今日新增: {{ overviewData.todayNewComments || 0 }}
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-like">
            <i class="el-icon-thumb card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">总点赞数</div>
            <count-to :start-val="0" :end-val="overviewData.totalLikes || 0" :duration="3500" class="card-panel-num" />
            <div class="card-panel-sub">
              今日新增: {{ overviewData.todayNewLikes || 0 }}
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="32" style="margin-top: 32px;">
      <!-- 用户增长趋势图 -->
      <el-col :xs="24" :sm="24" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>用户增长趋势（最近30天）</span>
          </div>
          <div ref="userTrendChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
      
      <!-- 视频增长趋势图 -->
      <el-col :xs="24" :sm="24" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>视频增长趋势（最近30天）</span>
          </div>
          <div ref="videoTrendChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="32" style="margin-top: 32px;">
      <!-- 视频分类统计饼图 -->
      <el-col :xs="24" :sm="24" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>视频分类统计</span>
          </div>
          <div ref="categoryChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
      
      <!-- 用户活跃度统计 -->
      <el-col :xs="24" :sm="24" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>用户活跃度（最近7天）</span>
          </div>
          <div ref="activityChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import { getOverview, getUserTrend, getVideoTrend, getCategoryStats, getUserActivity } from '@/api/dashboard'
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  components: {
    CountTo
  },
  data() {
    return {
      overviewData: {},
      userTrendChart: null,
      videoTrendChart: null,
      categoryChart: null,
      activityChart: null
    }
  },
  mounted() {
    this.initCharts()
    this.fetchData()
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    if (this.userTrendChart) {
      this.userTrendChart.dispose()
    }
    if (this.videoTrendChart) {
      this.videoTrendChart.dispose()
    }
    if (this.categoryChart) {
      this.categoryChart.dispose()
    }
    if (this.activityChart) {
      this.activityChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.userTrendChart = echarts.init(this.$refs.userTrendChart)
      this.videoTrendChart = echarts.init(this.$refs.videoTrendChart)
      this.categoryChart = echarts.init(this.$refs.categoryChart)
      this.activityChart = echarts.init(this.$refs.activityChart)
    },
    
    // 获取数据
    async fetchData() {
      try {
        // 获取概览数据
        const overviewRes = await getOverview()
        this.overviewData = overviewRes.data

        // 获取并渲染用户趋势图
        const userTrendRes = await getUserTrend()
        this.renderUserTrendChart(userTrendRes.data)

        // 获取并渲染视频趋势图
        const videoTrendRes = await getVideoTrend()
        this.renderVideoTrendChart(videoTrendRes.data)

        // 获取并渲染分类统计图
        const categoryRes = await getCategoryStats()
        this.renderCategoryChart(categoryRes.data)

        // 获取并渲染活跃度统计图
        const activityRes = await getUserActivity()
        this.renderActivityChart(activityRes.data)
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('数据加载失败')
      }
    },
    
    // 渲染用户增长趋势图
    renderUserTrendChart(data) {
      const option = {
        title: {
          text: '用户增长',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.date),
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '新增用户',
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '累计用户',
            position: 'right',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '新增用户',
            type: 'bar',
            data: data.map(item => item.count),
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '累计用户',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => item.total),
            itemStyle: {
              color: '#67C23A'
            },
            lineStyle: {
              width: 3
            }
          }
        ]
      }
      this.userTrendChart.setOption(option)
    },
    
    // 渲染视频增长趋势图
    renderVideoTrendChart(data) {
      const option = {
        title: {
          text: '视频增长',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.date),
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '新增视频',
            position: 'left'
          },
          {
            type: 'value',
            name: '累计视频',
            position: 'right'
          }
        ],
        series: [
          {
            name: '新增视频',
            type: 'bar',
            data: data.map(item => item.count),
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            name: '累计视频',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => item.total),
            itemStyle: {
              color: '#F56C6C'
            },
            lineStyle: {
              width: 3
            }
          }
        ]
      }
      this.videoTrendChart.setOption(option)
    },
    
    // 渲染分类统计饼图
    renderCategoryChart(data) {
      const option = {
        title: {
          text: '视频分类分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          bottom: '10%',
          left: 'center'
        },
        series: [
          {
            name: '视频分类',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '45%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data.map(item => ({
              value: item.videoCount,
              name: item.categoryName
            }))
          }
        ]
      }
      this.categoryChart.setOption(option)
    },
    
    // 渲染用户活跃度图
    renderActivityChart(data) {
      const option = {
        title: {
          text: '用户活跃度',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#606266'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.date),
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '活跃用户数'
        },
        series: [
          {
            name: '活跃用户',
            type: 'line',
            data: data.map(item => item.activeUsers),
            smooth: true,
            itemStyle: {
              color: '#909399'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(144, 147, 153, 0.3)'
                }, {
                  offset: 1, color: 'rgba(144, 147, 153, 0.1)'
                }]
              }
            }
          }
        ]
      }
      this.activityChart.setOption(option)
    },
    
    // 处理窗口大小变化
    handleResize() {
      if (this.userTrendChart) this.userTrendChart.resize()
      if (this.videoTrendChart) this.videoTrendChart.resize()
      if (this.categoryChart) this.categoryChart.resize()
      if (this.activityChart) this.activityChart.resize()
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 32px;
  background-color: #f0f2f5;
  min-height: 100vh;

  .panel-group {
    margin-bottom: 32px;

    .card-panel-col {
      margin-bottom: 32px;
    }

    .card-panel {
      height: 108px;
      cursor: pointer;
      font-size: 12px;
      position: relative;
      overflow: hidden;
      color: #666;
      background: #fff;
      box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
      border-color: rgba(0, 0, 0, .05);
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, .15);
      }

      .icon-user .card-panel-icon {
        color: #40c9c6;
      }

      .icon-video .card-panel-icon {
        color: #36a3f7;
      }

      .icon-comment .card-panel-icon {
        color: #f4516c;
      }

      .icon-like .card-panel-icon {
        color: #34bfa3;
      }

      .card-panel-icon-wrapper {
        float: left;
        margin: 14px 0 0 14px;
        padding: 16px;
        transition: all 0.38s ease-out;
        border-radius: 8px;
      }

      .card-panel-icon {
        float: left;
        font-size: 48px;
      }

      .card-panel-description {
        float: right;
        font-weight: bold;
        margin: 26px 26px 26px 0;

        .card-panel-text {
          line-height: 18px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 16px;
          margin-bottom: 12px;
        }

        .card-panel-num {
          font-size: 20px;
          color: rgba(0, 0, 0, 0.85);
        }

        .card-panel-sub {
          font-size: 12px;
          color: rgba(0, 0, 0, 0.45);
          margin-top: 8px;
        }
      }
    }
  }

  .chart-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border: none;
    margin-bottom: 32px;

    .chart-header {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
}

@media (max-width: 1024px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>
